﻿#include "ZmqReplyer.h"

#include <iostream>
#include <vector>

#define CLI_CR_RED          "\033[31m"
#define CLI_CR_YELLOW       "\033[33m"
#define CLI_CR_CLOSE        "\033[0m"

ZmqReplyer::ZmqReplyer()
{
	m_context = NULL;
	m_socket = NULL;
}

ZmqReplyer::~ZmqReplyer()
{
}

int ZmqReplyer::Bind(const char*  szSvrIp, int port)
{
	char address[64];
	sprintf(address, "tcp://%s:%d", szSvrIp, port);
	return Bind(address);
}

int ZmqReplyer::Bind(const char *address)
{
	m_context = zmq_ctx_new();

	if (!m_context) 
	{
		std::cerr << CLI_CR_RED << "[Replier] " << "CReplier::failed to create context! with error :" << zmq_strerror(zmq_errno()) << std::endl << CLI_CR_CLOSE;
		return -1;
	}

	m_socket = zmq_socket(m_context, ZMQ_REP);

	if (!m_socket) 
	{
		std::cerr << CLI_CR_RED << "[Replier] " << "CReplier::failed to create publiser socket! with error :" << zmq_strerror(zmq_errno()) << std::endl << CLI_CR_CLOSE;
		return -2;
	}

	int ret = zmq_bind(m_socket, address);
	if (ret <0) 
	{
		std::cerr << CLI_CR_RED << "[Replier] " << "CReplier::Reply socket failed to bind port number :" << address << " with return value :" << ret << "with error :" << zmq_strerror(zmq_errno()) << std::endl << CLI_CR_CLOSE;
		return ret;
	}
	else
	{
		std::cout << "[Replier] " << "CReplier::Create REPLY server,bind with address :" << address << std::endl;
		//m_bMonitorReply = true;
		//m_thread = new std::thread(ZmqReplyer::threadEntry, this);
	}

	return 0;
}

int ZmqReplyer::resv(char *data, int length)
{
	zmq_msg_t request; // 创建消息结构化  空的
	zmq_msg_init(&request); // 初始消息  
	zmq_recv(m_socket, &request, sizeof(request), 0); // 从管道中接收消息  
	memcpy(data, zmq_msg_data(&request), sizeof(request));
	length = sizeof(data);
	zmq_msg_close(&request); // 销毁消息  
	Sleep(1000);
	return 0;
}

int ZmqReplyer::send(const char *data, int length)
{
	zmq_msg_t reply; // 创建reply消息的结构  
	zmq_msg_init_size(&reply, strlen(data)+1); // 初始化5个字节的消息来容纳“World”  
	memcpy(zmq_msg_data(&reply), data, strlen(data) + 1); // 拷贝到消息中  
	zmq_send(m_socket, &reply, sizeof(reply), 0); // 发送消息到管道，等待io_thread从管道中读取后发送  
	zmq_msg_close(&reply);
	return 0;
}
